const fs = require('fs')

const readAndMatch = require('../../util/readAndMatch')
const createFoldersAndFiles = require('../script/createFoldersAndFiles')

function getModuleRsV0(vendors, target, regexName, regexSkeleton, regexAtlas, moreVision = false) {
  const filePath = vendors
  const regexPattern = regexAtlas
  const regexPattern2 = regexSkeleton
  const regexPattern3 = regexName
  const atlasDatas = readAndMatch(filePath, regexPattern)
  const skeletonDatas = readAndMatch(filePath, regexPattern2)
  const modules = []
  const errList = []

  if (atlasDatas.length !== skeletonDatas.length) {
    return {
      success: false,
      message: '获取材质和模型不匹配，请手动获取……',
    }
  }

  let n = atlasDatas.length
  const nameReg = new RegExp(regexPattern3)
  if (!fs.existsSync(target) || !fs.lstatSync(target).isDirectory()) {
    fs.mkdirSync(target)
  }
  console.log('开始拆解文件……')
  for (let i = 0; i < n; i++) {
    try {
      const skeletonData = skeletonDatas[i]
      const atlasData = atlasDatas[i]

      const fileNameMatch = atlasData.match(nameReg)
      const fileName = fileNameMatch[0].slice(13, -4)
      const skeletonText = skeletonData.slice(24, -3)
      const atlasText = atlasData.slice(13, -2)

      try {
        createFoldersAndFiles(target, fileName, skeletonText, atlasText, moreVision)
        modules.push(fileName)
        console.log(`${fileName} 拆解完成`)
      } catch (e) {
        errList.push(fileName)
        console.log(`${fileName} 拆解失败`)
      }
    } catch (e) {

    }
  }

  return {
    modules,
    errList,
  }
}

module.exports = getModuleRsV0
